<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 300px;
            height: 100px;
            background: red;
            position: absolute;
            left: 50%;
            transform: translate(-50%);
            top: 100px;
        }

        .container {
            width: 100px;
            height: 2000px;
            background: blue;
        }
    </style>
</head>

<body>
    <div class="container"></div>
    <div class="box"></div>
    <button class="btn">点击我回到顶部</button>
    <script>
        // 获取box元素
        var boxEle = document.getElementsByClassName("box")[0];
        var btnEle = document.getElementsByClassName("btn")[0];
        // 获取卷去的高度
        window.onscroll = function () {
            var top = document.documentElement.scrollTop || document.body.scrollTop;
            console.log(top);
            if (top > 100) {
                boxEle.style.position = "fixed";
                boxEle.style.top = 0;
            } else {
                boxEle.style.position = "absolute";
                boxEle.style.top = "100px";
            }

        }

        btnEle.onclick = function () {
            // document.documentElement.scrollTop = 0;

            var top = document.documentElement.scrollTop;
            // console.log(top);
            // setTimeout(function () {
            //     top -= 100;
            //     document.documentElement.scrollTop = top;
            //     setTimeout(function () {
            //         top -= 100;
            //         document.documentElement.scrollTop = top;
            //         setTimeout(function () {
            //             top -= 100;
            //             document.documentElement.scrollTop = top;
            //         }, 500);
            //     }, 500);
            // }, 500);


            function setTop(){
                setTimeout(function(){
                    top -= 100;
                    document.documentElement.scrollTop = top;
                    if(top>0){  // 递归给出口
                        setTop();
                    }
                }, 5);
            }
            setTop();      

        }




    </script>
</body>

</html>